package com.lagou.task.dao;

import com.lagou.task.model.Admin;
import com.lagou.task.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class AdminDaoImp implements AdminDao{

    @Override
    public Admin userLogin(Admin admin) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            // 1.获取数据库连接
            connection = DBUtil.getConnection();
            // 2.准备sql语句
            String sql = "select * from t_user where username = ? and password =?";
            // 3.执行sql语句后获取结果并返回
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,admin.getUsername());
            preparedStatement.setString(2, admin.getPassword());
            resultSet = preparedStatement.executeQuery();
            if(resultSet.next()){
                Admin tu = new Admin(resultSet.getString("username"),resultSet.getString("password"));
                return tu;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 4.释放资源
            try {
                DBUtil.closeSource(connection,preparedStatement);
                if(null !=resultSet){
                    resultSet.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

